#!/bin/bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
ZEN_ROOT=$(realpath $SCRIPT_DIR/../..)

die() { echo "ERROR: $1"; exit; }

if [ -z $1 ]; then
	echo "usage: $(basename ${BASH_SOURCE[0]}) <output_dir>"
	exit
fi

if [ -e $1 ]; then
	rmdir $1
	if [ $? -gt 0 ]; then
		die "$1 is not empty"
		exit
	fi
fi

mkdir -p $1
cd $1

mkdir -p tmp
cd tmp

#CLANG_VERSION=v21_clang-15.0.1-centos7
CLANG_VERSION=v22_clang-16.0.6-centos7
TOOLCHAIN_PLATFORM=x86_64-unknown-linux-gnu

echo "Fetching UE toolchain $CLANG_VERSION..."
wget -q --show-progress http://cdn.unrealengine.com/Toolchain_Linux/native-linux-$CLANG_VERSION.tar.gz

echo "Extracting toolchain $TOOLCHAIN_PLATFORM..."
tar -xzf native-linux-$CLANG_VERSION.tar.gz $CLANG_VERSION/$TOOLCHAIN_PLATFORM/
mv $CLANG_VERSION/$TOOLCHAIN_PLATFORM/* ..

cd ..
rm -rf tmp

rm -rf usr/lib
mkdir -p usr/lib
mv usr/lib64/*.o usr/lib

echo "Fetching UE headers and libc++ from $ZEN_ROOT/thirdparty/ue-libcxx..."
cp -r $ZEN_ROOT/thirdparty/ue-libcxx/include/* ./include
mkdir -p ./lib64
cp -r $ZEN_ROOT/thirdparty/ue-libcxx/lib64/* ./lib64

echo "Done"
